# -*- coding: utf-8 -*-
from PySide2 import QtWidgets 
from PySide2 import QtCore
from PySide2 import QtGui
import maya.cmds as mc
import maya.mel as mel
import os, re
import DH_PySideUidata
from DHAnimation import DH_setHeadsUpDisplay
reload (DH_setHeadsUpDisplay)

filepath = str(os.path.split(os.path.realpath(__file__))[0])
form_class, base_class = DH_PySideUidata.loadUiType(filepath+'/DH_assetProxyManager.ui')

ref_dir = "Y:/XCM_2019DY/Asset/seq000/character/CA004009xryrz/scenes/rigging"
ref_HB = ["_H_","_B_","_L_"]

class DH_proxyManager(base_class, form_class):

    def __init__(self):
        self.window_name = 'DH_assetProxyManagerWindow'
        if mc.window(self.window_name, exists=True):
            mc.deleteUI(self.window_name)
        super(DH_proxyManager, self).__init__(parent=DH_PySideUidata.getMayaWindow())
        self.setupUi(self)
        desktop = QtWidgets.QApplication.desktop().availableGeometry()
        size = self.geometry()
        self.move((desktop.width()-size.width())/2, (desktop.height()-size.height())/2)
        
        self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)#allow right click pop menu
        self.tableWidget.customContextMenuRequested.connect(self.switchMenu)#right clicked pop menu
        
        self.tableWidget.horizontalHeader().sectionClicked.connect(self.list_selected_refProxy)
        self.tableWidget.clicked.connect(self.list_selected_refProxy)#refresh the Proxy refnode in the right tableWidget
       
        self.ref_type = self.comboBox_2.currentText()
               
        self.addItems() 
        self.setItemColor() 

    def list_selected_refProxy(self):
        self.tableWidget1.clearContents()
        #print "hi"
        selected_row = []
        selected_items = self.tableWidget.selectedItems()
        
        for i in selected_items:
            if self.tableWidget.indexFromItem(i).row() not in selected_row:
                selected_row.append(self.tableWidget.indexFromItem(i).row())
        self.tableWidget1.setRowCount(len(selected_row))
        #print selected_row
        j = 0
        for raw in selected_row:
            selected_item = self.tableWidget.item(raw,0).text().replace(ref_HB[1],ref_HB[0],1)#get the selected item
            
            if not re.findall("Proxy",selected_item):
                if selected_item[-1]!="N":
                    selected_item_proxy = selected_item+"ProxyRN"
                else:
                    selected_item_proxy = selected_item.replace("RN","ProxyRN")    
            else:
                selected_item_proxy = selected_item
            
            if mc.objExists(selected_item_proxy):
                new_item = QtWidgets.QTableWidgetItem(selected_item_proxy)
                #new_item.setBackgroundColor(QtGui.QColor(70,30,10))
                self.tableWidget1.setItem(j,0,new_item)
                j += 1
    def getAllrefNodes(self): 
        #global ref_type
        allrefNodes = mc.file(q=1,r=1)#list all ref nodes in the scene
        all_selected_refnodes = [] 
        for  ref_node in allrefNodes:
            if(self.ref_type == ref_node.split("/")[4]): #if this node is a character
                if(mc.referenceQuery(ref_node,il=True)): #if this refnode is loaded
                    ref_node_name = mc.referenceQuery(ref_node,rfn=True)
                    #print ref_node_name 
                    all_selected_refnodes.append(ref_node_name) # then add it to the return list
        #print all_selected_refnodes
        return all_selected_refnodes
    def addItems(self): #add new items of all found refnodes
        self.tableWidget.clearContents()
        all_selected_refnodes = self.getAllrefNodes()#get all loaded refnodes
        i = 0
        self.tableWidget.setRowCount(len(all_selected_refnodes))
        for _ in all_selected_refnodes:
            label=_
            #print "14654515"+label
            new_item = QtWidgets.QTableWidgetItem(label)
            self.tableWidget.setItem(i,0,new_item)
            #print "51456456"+self.tableWidget.item(i,0).text()
            i+=1
        
        
    def setItemColor(self):#set high asset bgcolor to red or low  to green
        raws = self.tableWidget.rowCount()
        for _ in range(raws):
            #print self.tableWidget.item(raw_index,0).text()
            label_temp = self.tableWidget.item(_,0).text()
            label = mc.referenceQuery(label_temp,rfn=True)
            colorCondition = mc.referenceQuery(label_temp,f=True)
            new_item = QtWidgets.QTableWidgetItem(label)
            if not re.findall("Proxy",label) and not re.findall(ref_HB[2],label):
                new_item.setBackgroundColor(QtGui.QColor(100,10,10))#set _H_ to red
            elif re.findall("Proxy",label) and not re.findall(ref_HB[2],label):
                new_item.setBackgroundColor(QtGui.QColor(10,100,10))    #set _B_ to green
            
            self.tableWidget.setItem(_,0,new_item)
    def switchMenu(self,pos):#add menuItems to right click pop menu
        #print pos
        switch_menu = QtWidgets.QMenu()
        item1 = switch_menu.addAction(u"增加代理".encode('utf-8'))
        item2 = switch_menu.addAction(u"移除代理".encode('utf-8'))
        action = switch_menu.exec_(self.tableWidget.mapToGlobal(pos))
        if action == item1:
            self.switch_action()#replace asset
        elif action == item2:
            self.remove_action()#remove low asset
            
    def erroroutput(self,errorContent):
        mc.confirmDialog(title='Confirm', message=errorContent, button=['ok'])


    
    def switch_action(self):
        #print "hi"
        #get selected raws
        global ref_HB
        selected_row = []
        selected_items = self.tableWidget.selectedItems()
        for i in selected_items:
            if self.tableWidget.indexFromItem(i).row() not in selected_row:
                selected_row.append(self.tableWidget.indexFromItem(i).row())
        #switch assets
        mel.eval("optionVar -iv proxyOptionsSharedEdits  1")#before switching,you must turn on the share edits  of the proxyAdd option to keep the animation between assets
        #now start switching
        for j in selected_row:
            selected_item = self.tableWidget.item(j,0).text()#get the selected item
            if re.findall(ref_HB[2],selected_item):
                self.erroroutput(u"请将该角色切换成高模:\n %s"%selected_item.encode('gbk'))
                continue
            #ref_dir = ref_dir.replace(ref_dir.split("/")[5],selected_item.split("_")[3],1)
            #selected_item_fullpath = ref_dir + "/" + selected_item.replace(ref_HB[0],ref_HB[1],1)+".mb"
            selected_item_fullpath = mc.referenceQuery(selected_item,f = 1)#get full path of selected item
            
            if not re.findall("Proxy",selected_item):
                selected_item_ref = selected_item
                if selected_item[-1]!="N":
                    selected_item_proxy = selected_item+"ProxyRN"
                else:
                    selected_item_proxy = selected_item.replace("RN","ProxyRN")    
            else:
                if len(selected_item.split("_")[-1])>11:
                    #print re.findall("RN",selected_item)
                    selected_item_ref = selected_item.replace("ProxyRN","")
                else:
                    selected_item_ref = selected_item.replace("Proxy","")
                #print selected_item_ref 
                selected_item_proxy = selected_item  
            #if mc.objExists(selected_item_ref.replace("_rig","_ms_anim",1)):
                #selected_item_ref = selected_item_ref.replace("_rig","_ms_anim",1)#format like this XCM_2019DY_CH_QzYerennanL_H_seq000_ms_animRN1
                #selected_item_proxy = selected_item.replace(ref_HB[1],ref_HB[0],1).replace("_rig","_ms_animProxy",1)#XCM_2019DY_CH_QzYerennanL_H_seq000_ms_animProxyRN1
            #else:
                #selected_item_ref = selected_item.replace(ref_HB[1],ref_HB[0],1)#format like this XCM_2019DY_CH_QzYerennanL_H_seq000_rigRN1
            #format like this XCM_2019DY_CH_QzYerennanL_H_seq000_rigProxyRN1
            #print selected_item_proxy
            #check if this is the first time to add a proxy
            if mc.objExists(selected_item_proxy):
                if not re.findall("Proxy",selected_item):#if this is a H refNode
                    # mel.eval("proxySwitch %s;"%selected_item_proxy)
                    pass
                else:#if this is a B refNode
                    # mel.eval("proxySwitch %s;"%selected_item_ref)
                    pass
            elif not (re.findall(ref_HB[2],selected_item) and  re.findall(ref_HB[1],selected_item)):#if there's no proxyrefNode of this refNode
                selected_item_fullpath = selected_item_fullpath.split("{")[0].replace(ref_HB[0],ref_HB[1],1)
                print selected_item_ref
                print selected_item_fullpath
                if os.path.isfile(selected_item_fullpath):
                    mel.eval('proxyAdd "%s" "%s" "%s";'%(selected_item_ref,selected_item_fullpath,"Proxy"))
                    # mel.eval("proxySwitch %s;"%selected_item_proxy)
                else:
                    self.erroroutput(u"所选选项有代理文件不存在！请联系TD".encode('gbk'))
                    continue
            #print selected_item_fullpath
        self.addItems() 
        self.setItemColor()
                    
    def remove_action(self):#this method is similar to the last one
        global ref_HB
        selected_row = []
        selected_items = self.tableWidget.selectedItems()
        for i in selected_items:
            if self.tableWidget.indexFromItem(i).row() not in selected_row:
                selected_row.append(self.tableWidget.indexFromItem(i).row())
        for j in selected_row:
            selected_item = self.tableWidget.item(j,0).text().split(":")[-1]#get the selected item
            #print "11111---"+selected_item
            selected_item_ref = selected_item.replace(ref_HB[1],ref_HB[0],1)# format like this XCM_2019DY_CH_QzYerennanL_H_seq000_rigRN1
           
            if re.findall("Proxy",selected_item):
                #print(u"请先切换到高模再移除".encode('gbk'))
                self.erroroutput(u"请先切换到高模再移除".encode('gbk'))
            else:
                '''
                if mc.objExists(selected_item_ref.replace("_rig","_ms_anim",1)):
                    #print "di111ge---"+selected_item
                    selected_item_proxy = selected_item.replace(ref_HB[1],ref_HB[0],1).replace("_ms_anim","_ms_animProxy",1)
                    #print "di111ge---"+selected_item_proxy
                else:
                    #print "di00000---"+selected_item
                    selected_item_proxy = selected_item.replace(ref_HB[1],ref_HB[0],1).replace("RN","ProxyRN")#format like this XCM_2019DY_CH_QzYerennanL_H_seq000_rigProxyRN1
                    #print "di00000---"+selected_item
                    print "di222ge---"+selected_item_proxy
                print "di333ge---" + selected_item_proxy
                '''
                if selected_item[-1]!="N":
                    selected_item_proxy = selected_item+"ProxyRN"
                else:
                    selected_item_proxy = selected_item.replace("RN","ProxyRN")                    
                if mc.objExists(selected_item_proxy):
                    mel.eval("proxyRemove %s"%selected_item_proxy)
                else:
                    #print(u"当前引用无代理，请先增加代理".encode('gbk'))
                    self.erroroutput(u"当前引用无代理或处于低模状态，请检查".encode('gbk'))
                    continue
        self.erroroutput(u"请在referenceEditor中检查是否有未移除的代理")
        mel.eval("ReferenceEditor")
        self.addItems() 
        self.setItemColor()

    







